package com.xiaoke.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoke.domain.entity.LoginUser;
import com.xiaoke.domain.entity.User;
import com.xiaoke.exception.QueryException;
import com.xiaoke.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service("userDetailsService")
public class UserDatailsServiceImpl implements UserDetailsService {
    @Resource
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1，根据用户名获取用户
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);

        User user = userMapper.selectOne(lambdaQueryWrapper);

        if(Objects.isNull(user)) {
            throw new RuntimeException("用户名不存在！");
        }

        // TODO  2. 查询权限
        // 3. 返回 UserDetails
        return new LoginUser(user,null);
    }
}
